import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/config/config.dart';
import 'package:tiktokadult/hj_model/user/user_info_model.dart';
import 'package:tiktokadult/hj_utils/holiday_theme.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/widget/common_dialog.dart';
import 'package:tiktokadult/tools_base/widget/net_image_widget.dart';

import '../../config/address.dart';
import '../../hj_model/video_model.dart';
import '../../hj_utils/global.dart';
import '../../hj_utils/light_model.dart';
import '../../hj_utils/store_keys.dart';
import '../../tools_base/global_store/store.dart';

///分享二维码对话框
class ShareVideoDialog extends StatefulWidget {
  final VideoModel? videoModel;
  final bool isCoverV;

  ShareVideoDialog({
    this.videoModel,
    this.isCoverV = false,
  });

  @override
  State<StatefulWidget> createState() {
    return _ShareVideoDialogState();
  }
}

class _ShareVideoDialogState extends State<ShareVideoDialog> with TickerProviderStateMixin {
  UserInfoModel? get userInfo => globalStore.getMe();
  GlobalKey globalKey = GlobalKey();
  String? shareUrl;

  @override
  void initState() {
    super.initState();
    shareUrl = userInfo?.promoteURL ?? "";
  }

  /// 复制链接
  _onCopyLink() {
    if (shareUrl?.isNotEmpty == true) {
      Clipboard.setData(ClipboardData(text: shareUrl ?? ""));
      showToast("复制成功，快去分享吧");
      Get.back();
    } else {
      showToast("链接生成错误");
    }
  }

  /// 保存图片
  void _onSaveImg() async {
    await _capturePngAndSaveToGallery();
    setState(() {});
    showToast("保存成功，快去分享吧");
  }

  /// 将组件转化为图片数据
  Future<void> _capturePngAndSaveToGallery() async {
    RenderRepaintBoundary? boundary = globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
    ui.Image? image = await boundary?.toImage(pixelRatio: 3.0);
    ByteData? byteData = await image?.toByteData(format: ui.ImageByteFormat.png);
    await savePngDataToAblumn(byteData?.buffer.asUint8List());
  }

  /// 保存数据到相册
  Future<bool> savePngDataToAblumn(Uint8List? pngBytes) async {
    if (pngBytes == null) return false;
    var map = await ImageGallerySaver.saveImage(pngBytes);
    if (null != map && map["isSuccess"] == true) {
      showToast("保存成功");
      lightKV.setBool(StoreKeys.HAVE_SAVE_QR_CODE, true);
      Get.back();
      return true;
    } else {
      showToast("保存失败，请手动截图");
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return CommonDialog(
      padding: EdgeInsets.zero,
      child: _buildContetnt(),
    );
  }

  _buildContetnt() {
    return RepaintBoundary(
      key: globalKey,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 23, vertical: 32),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              children: [
                Image.asset(
                  HolidayTheme.theme.appIcon,
                  width: 48.w,
                  height: 48.w,
                ),
                10.w.sizeBoxW,
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text('${Config.APPNAME}',
                        style: TextStyle(color: Colors.white.withOpacity(.9), fontWeight: FontWeight.w500, fontSize: 14)),
                    4.sizeBoxH,
                    Text("记录美好性生活", style: TextStyle(color: Color(0xFFFFFFff).withOpacity(.45), fontSize: 10)),
                  ],
                ),
              ],
            ),
            18.sizeBoxH,
            Container(
              // constraints: BoxConstraints(maxHeight: 200),
              padding: EdgeInsets.symmetric(horizontal: 27),
              child: NetworkImageLoader(
                width: double.infinity,
                imageUrl: widget.videoModel?.cover ?? "",
                fit: BoxFit.fitHeight,
              ),
            ),
            18.sizeBoxH,
            Column(
              children: [
                Row(
                  children: [
                    Container(
                      width: 94,
                      height: 94,
                      padding: EdgeInsets.all(2),
                      color: Colors.white,
                      child: QrImageView(
                        data: shareUrl ?? '',
                        padding: EdgeInsets.zero,
                      ),
                    ),
                    SizedBox(width: 6),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            "邀请码${userInfo?.promotionCode}", //_getPublisherName(),
                            style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: Colors.white.withOpacity(.9)),
                          ),
                          20.sizeBoxH,
                          Text(
                            '官方网址:${Address.groundURl ?? ""}',
                            maxLines: 2,
                            style: TextStyle(
                              fontSize: 10,
                              color: Colors.white.withOpacity(.45),
                            ),
                          ),
                        ],
                      ),
                    )
                  ],
                ),
                24.sizeBoxH,
                Row(
                  children: [
                    Expanded(
                      child: InkWell(
                        onTap: () => _onCopyLink(),
                        child: Container(
                          width: 112,
                          height: 44,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(3),
                            color: Colors.white.withOpacity(.1),
                          ),
                          child: Text(
                            "复制链接",
                            style: TextStyle(
                              fontSize: 16,
                              color: Color(0xff989898),
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                    ),
                    16.sizeBoxW,
                    Expanded(
                      child: InkWell(
                        onTap: () => _onSaveImg(),
                        child: Container(
                          height: 44,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(3),
                            color: AppColors.actionRed,
                          ),
                          child: Text(
                            "保存图片",
                            style: TextStyle(
                              fontSize: 16,
                              color: Colors.white,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
